package com.example.finalhomework.cardgame.ui

import android.content.res.Configuration
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.cardgame.model2.Card
import com.example.finalhomework.R
import com.example.finalhomework.cardgame.viewmodel.AdvancedCardGameViewModel

@Composable
fun AdvancedCardGameScreen(navController: NavController, viewModel: AdvancedCardGameViewModel = viewModel()) {
    // 获取当前上下文
    val context = LocalContext.current
    // 获取当前设备的配置（如屏幕方向）
    val configuration = LocalConfiguration.current
    // 根据屏幕方向设置列数，竖屏4列，横屏6列
    val columns = if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) 4 else 6
    // 定义重置对话框的显示状态
    val showResetDialog = remember { mutableStateOf(false) }
    // 定义结束对话框的显示状态
    val showFinishDialog = remember { mutableStateOf(false) }

    Log.d("AdvancedCardGameScreen", "AdvancedCardGameScreen Composable executed")

    // 使用Column布局来垂直排列组件
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        // 显示当前分数
        Text(text = "Score: ${viewModel.score}", modifier = Modifier.padding(16.dp))

        // 使用LazyVerticalGrid来显示卡片网格
        LazyVerticalGrid(
            columns = GridCells.Fixed(columns),
            modifier = Modifier.weight(1f)
        ) {
            // 遍历卡片列表并显示每张卡片
            items(viewModel.game.cards.size) { index ->
                val card = viewModel.game.cards[index]
                CardItem(card, onClick = {
                    viewModel.chooseCardAtIndex(index)
                    Log.d("AdvancedCardGameScreen", "Card at index $index clicked")
                })
            }
        }

        // 使用Row布局来水平排列按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            // 重置按钮，点击时显示重置对话框
            Button(onClick = {
                showResetDialog.value = true
                Log.d("AdvancedCardGameScreen", "Reset button clicked")
            }) {
                Text(text = "Reset")
            }

            // 结束按钮，点击时显示结束对话框
            Button(onClick = {
                showFinishDialog.value = true
                Log.d("AdvancedCardGameScreen", "Finish button clicked")
            }) {
                Text(text = "Finish")
            }
        }

        // 如果重置对话框显示状态为true，则显示重置对话框
        if (showResetDialog.value) {
            AlertDialog(
                onDismissRequest = { showResetDialog.value = false },
                title = { Text(text = "Confirm Reset") },
                text = { Text(text = "Are you sure you want to reset the game?") },
                confirmButton = {
                    Button(onClick = {
                        showResetDialog.value = false
                        viewModel.resetGame()
                        Log.d("AdvancedCardGameScreen", "Game reset confirmed")
                    }) {
                        Text("Yes")
                    }
                },
                dismissButton = {
                    Button(onClick = { showResetDialog.value = false }) {
                        Text("No")
                    }
                }
            )
        }

        // 如果结束对话框显示状态为true，则显示结束对话框
        if (showFinishDialog.value) {
            AlertDialog(
                onDismissRequest = { showFinishDialog.value = false },
                title = { Text(text = "Confirm Finish") },
                text = { Text(text = "Are you sure you want to finish the game?") },
                confirmButton = {
                    Button(onClick = {
                        showFinishDialog.value = false
                        viewModel.updateHighestScore(context)
                        navController.navigate("PersonalInfo")
                        Log.d("AdvancedCardGameScreen", "Game finish confirmed, navigating to PersonalInfo")
                    }) {
                        Text("Yes")
                    }
                },
                dismissButton = {
                    Button(onClick = { showFinishDialog.value = false }) {
                        Text("No")
                    }
                }
            )
        }
    }
}


//显示卡片的视图
@Composable
fun CardItem(card: Card, onClick: () -> Unit) {
    // 加载卡片背面图片
    val cardBack: Painter = painterResource(id = R.drawable.card_back)
    // 使用Box布局来显示卡片
    Box(
        modifier = Modifier
            .padding(8.dp)
//            .size(60.dp)
            .width(80.dp)
            .height(120.dp)
            .clickable {
                onClick()
                Log.d("AdvancedCardGameScreen", "Card clicked: ${card.getDisplayValue()}")
            }
            .border(1.dp, Color.Black, RoundedCornerShape(8.dp)),
        contentAlignment = Alignment.Center
    ) {
        // 如果卡片被选中则显示正面，否则显示背面
        if (card.isChosen) {
            Text(text = card.getDisplayValue())
        } else {
            Image(painter = cardBack, contentDescription = "Card Back")
        }
    }
}

@Preview
@Composable
fun PreviewAdvancedCardGameScreen() {
    AdvancedCardGameScreen(navController = NavController(LocalContext.current))
}